package com.leyou.item.config;

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.concurrent.TimeUnit;

@Configuration
public class RedisConfig {
    /**
     * 获取redis分布式锁脚本初始化
     * @return
     */
    @Bean
    public DefaultRedisScript<Long> lockScript(){
        DefaultRedisScript<Long> lockScript = new DefaultRedisScript<>();
        lockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("/lock.lua")));
        lockScript.setResultType(Long.class);
        return lockScript;
    }

    /**
     * 释放redis分布式锁脚本初始化
     * @return
     */
    @Bean
    public DefaultRedisScript<Long> unlockScript(){
        DefaultRedisScript<Long> unlockScript = new DefaultRedisScript<>();
        unlockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("/unlock.lua")));
        unlockScript.setResultType(Long.class);
        return unlockScript;
    }

    /**
     *
     * @return
     */
    @Bean
    public Retryer retryer(){
        return RetryerBuilder.<Long>newBuilder()
                .retryIfException()    //设置异常重试
                .retryIfResult(Predicates.equalTo(0L))    //call方法返回true重试
                .withWaitStrategy(WaitStrategies.fixedWait(1L, TimeUnit.SECONDS))   //设置1秒后重试
                .withStopStrategy(StopStrategies.stopAfterDelay(2500L,TimeUnit.MILLISECONDS)) //设置最长允许执行时间
                .build();
    }
}
